<template>
  <div ref="container" class="figure-container" @click="rotateMode" id="canvasId1"></div>
</template>

<script>
import * as THREE from 'three';
import { onMounted, ref } from 'vue';
// import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
export default {
  name: 'MultiTextureFigure',
  setup() {
    // 射线投射器
    const raycaster = new THREE.Raycaster();
    // 鼠标位置
    const mouse = new THREE.Vector2();
    // const gui = new GUI();
    const container = ref(null);
    let scene, camera, renderer;
    let mouseX = 0;
    let mouseY = 0; 
    let rotateTime = false;
    let leftEye; //眼睛左
    let rightEye; //眼睛右
    let leftPupil; //瞳孔
    let rightPupil; //瞳孔
    let blinkInterval; // 用于存储眨眼动画的定时器
    let windowHalfX = window.innerWidth / 2;
    let windowHalfY = window.innerHeight / 2;
    let targetRotationX = 0;
    let targetRotationY = 0;
    const rotationIntensity = 0.1; // 旋转强度系数
    let model 
    let headMesh; 
    const textureLoader = new THREE.TextureLoader();
    // 旋转动画相关变量
    let isRotating = false;
    let targetRotation = 0;
    let currentRotation = 0;
    const rotationSpeed = 0.12; // 旋转速度

    //初始化
    const init = () => {
      // 创建场景
      scene = new THREE.Scene();

      // 创建相机 视角,宽高比,最近平面,最远平面
      camera = new THREE.PerspectiveCamera(90, (window.innerHeight * 0.3) / (window.innerHeight * 0.2), 0.1, 2000);
      camera.position.z = 5;

      // 创建渲染器
      renderer = new THREE.WebGLRenderer({ alpha: true });
      renderer.setSize(window.innerHeight * 0.3, window.innerHeight * 0.2);
      container.value.appendChild(renderer.domElement);

      // 加载多张图片纹理
      // 添加环境光
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.6); // 颜色为白色，强度为0.5
      scene.add(ambientLight);
      // 关键设置：白色太阳光源（平行光）
      // const sunLight = new THREE.DirectionalLight(0xffffff, 1.5); // 强度设为1.5
      // sunLight.position.set(5, 10, 7); // 从斜上方照射
      // // sunLight.castShadow = true; // 启用阴影投射
      // scene.add(sunLight);
      const directions = [
        // { x: 1, y: 0, z: 0 }, // 右
        // { x: -1, y: 0, z: 0 }, // 左
        { x: 0, y: 1, z: 0 }, // 上
        { x: 0, y: -1, z: 0 }, // 下
        { x: 0, y: 0, z: 1 }, // 前
        { x: 0, y: 0, z: -1 }, // 后
      ];
      directions.forEach((dir, index) => {
        const light = new THREE.DirectionalLight(0xffffff, 3.2); // 每个方向光强度0.2
        light.position.set(dir.x * 5, dir.y * 5, dir.z * 5); // 远离模型
        light.castShadow = false; // 禁用阴影避免混乱
        scene.add(light);

        // 可选：添加光源可视化辅助
        // const helper = new THREE.DirectionalLightHelper(light, 1);
        // scene.add(helper);
      });

      //   // 创建几何体
      // const headGeometry = new THREE.SphereGeometry(2, 32, 32);
      const loader = new GLTFLoader();
      loader.load(
        'public/models/Yunduo11.glb',
        function (gltf) {
          // headMesh = gltf.scene;
          // console.log(gltf.scene, '获取动画');
          // headMesh.position.set(0, 0, 0);
          // headMesh.scale.set(3.5, 3.5, 3.5);
          // scene.add(headMesh);
           model = gltf.scene;
          const box = new THREE.Box3().setFromObject(model);
          const size = box.getSize(new THREE.Vector3());
          const center = box.getCenter(new THREE.Vector3());

          // 打印模型尺寸信息（调试用）
          console.log('模型尺寸:', size);
          console.log('模型中心:', center);
          // 1. 将模型中心移至场景原点
          model.position.x = -center.x * 0.5;
          model.position.y = -center.y;
          model.position.z = -center.z + 1.3;
          //   const light = new THREE.DirectionalLight(0xffffff, 4); // 每个方向光强度0.2
          // light.position.set( model.position.x, model.position.y,  -model.position.z); // 远离模型
          // light.castShadow = false; // 禁用阴影避免混乱
          // scene.add(light);
          // 2. 自动缩放模型以适应视口
          const maxDim = Math.max(size.x, size.y, size.z);
          const scale = 5 / maxDim; // 5是相机默认z位置，可根据需要调整
          // model.rotation.x = -Math.PI / 6;
          model.scale.set(scale, scale, scale);
          // model.traverse((child) => {
          //   if (child.isMesh) {
          //     console.log(child.material)
          //     child.material = new THREE.MeshStandardMaterial({
          //       // color: 0xffffff, // 基础颜色为白色
          //       // metalness: 1.0, // 完全金属化，增强反射
          //       // roughness: 0.0, // 完全光滑，镜面效果
          //       // envMapIntensity: .5, // 环境反射强度
          //     });
          //   }
          // });
          // 3. 应用变换
          model.updateMatrixWorld();

          // 将模型添加到场景
          scene.add(model);
        },
        undefined,
        function (error) {
          console.error('加载模型时出错:', error);
        },
      );

      window.addEventListener('resize', onWindowResize, false);

      // 开始动画循环
      document.addEventListener('mousemove', onDocumentMouseMove, false);

      function onDocumentMouseMove(event) {
        mouseX = (event.clientX / window.innerWidth) * 2 - 1;
        mouseY = -(event.clientY / window.innerHeight) * 2 + 1;

        // 计算目标旋转角度（限制在一定范围内）
        targetRotationY = mouseX * rotationIntensity;
        targetRotationX = -mouseY * rotationIntensity;
      }
      // function onDocumentMouseClick(event) {
      //   if (rotateTime) {
      //     return;
      //   }
      //   rotateTime = true;
      //   setTimeout(() => {
      //     rotateTime = false;
      //   }, 2000);
      //   // 将鼠标位置转换为归一化设备坐标（NDC）
      //   mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      //   mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

      //   // 更新射线投射器
      //   raycaster.setFromCamera(mouse, camera);

      //   // 射线与模型的交点
      //   const intersects = raycaster.intersectObjects([headMesh]);

      //   // if (intersects.length > 0) {
      //   console.log(intersects);
      //   // 点击到模型，开始旋转
      //   isRotating = true;
      //   targetRotation = currentRotation + Math.PI * 2;
      //   // }
      // }
      // container.value.addEventListener('click', onDocumentMouseClick, false);

      function animate() {
        requestAnimationFrame(animate);

        // 在这里可以添加动画逻辑
        // 例如：形象旋转
        //   scene.rotation.y += 0.01;
        // 平滑更新相机旋转
        const rotationFactor = 0.0004;
        const rotationX = mouseY * rotationFactor;
        const rotationY = mouseX * rotationFactor;

        // 更新模型旋转

        // if (isRotating) {
        //   // 计算本次旋转的增量
        //   const deltaRotation = Math.min(rotationSpeed, targetRotation - currentRotation);
        //   currentRotation += deltaRotation;
        //   headMesh.rotation.y += deltaRotation;

        //   if (currentRotation >= targetRotation) {
        //     // 旋转完成
        //     isRotating = false;
        //     currentRotation = targetRotation % (Math.PI * 2);
        //   }
        // } else {
        //   if (headMesh) {
        //     headMesh.rotation.x = rotationX;
        //     headMesh.rotation.y = rotationY;
        //   }
        // }
        // 渲染场景
        if (model) {
          model.rotation.y += (targetRotationY - model.rotation.y) * 0.1;
          model.rotation.x += (targetRotationX - model.rotation.x) * 0.1;
        }
        renderer.render(scene, camera);
      }
      animate();
    };
    const onWindowResize = () => {
      // camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      // renderer.setSize(window.innerWidth, window.innerHeight);
    };

    onMounted(() => {
      init();
    });

    return {
      container,
      headMesh,
    };
  },
};
</script>

<style scoped lang="less">
.figure-container {
  position: fixed;
  bottom: 50px;
  left: 20px;
  width: 30vh;
  height: 20vh;
  overflow: hidden;
  z-index: 999;
}
</style>
